import Router from '@koa/router';

import response from '../response.js';
import moment from 'moment';
import path from 'path';
import logger from '../logger.js';
import {createToken} from '../auth.js';

import db from '../mysqlHelper.js';
import { router } from './db.js';


router.prefix('/api');

router.post('/getTkoen', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if(body.appid==null){
        ctx.body = response.fail('缺少必填字段 appid');
        return;
    }
    if(body.appsecret==null){
        ctx.body = response.fail('缺少必填字段 appsecret'); 
        return;
    }
    if(body.appid!='1234567890' || body.appsecret!='1234567890'){
        ctx.body = response.fail('appid或appsecret错误');
        return;
    }
    let token = await createToken({appid:body.appid});
    ctx.body = response.success(token, '获取token成功');
});


//充电桩服务获取充电规则
router.post('/charge/getChargeRules', async (ctx) => {
    let body = ctx.request.body;
    if (body == null) {
        ctx.body = response.fail('参数不允许为空');
        return;
    }
    if (body.sn ==null) {
        ctx.body = response.fail('缺少必填字段 sn');
        return;
    }
    let sql = `select project_id from  charging_station where sn='${body.sn}'`;
    let result = await db.query(sql);
    if( result instanceof Error){
        console.error(`获取项目id失败 error :` + result.message, `sn:${body.sn}`);
        ctx.body = response.fail('获取项目id失败');
        return;
    }
    if (result.length == 0) {
        ctx.body = response.fail('获取项目id失败');
        return;
    }
    sql =`select id,rules_value,name from billing_rules where project_id='${result[0].project_id}' and type=0`;
    result = await db.query(sql);
    if (result instanceof Error) {
        console.error(`获取充电规则失败 error :` + result.message, `sn:${body.sn}`);
        ctx.body = response.fail('获取充电规则失败');
        return;
    }
    if (result.length == 0) {
        ctx.body = response.fail('该桩没有充电规则');
        return;
    }
    ctx.body = response.success(result, '获取成功');
});







export { router };

